package modeldemo.clint;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import modeldemo.model.User;
import modeldemo.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static modeldemo.utils.SignUtils.getSign;


/**
 * @Description:
 * @date 2023/3/14 10:04
 * @Modified By :
 */
public class Diaoyon {

    private static final String GATEWAY_HOST = "http://localhost:8090";

    private String accessKey;
    private String secretKey;

    public Diaoyon(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }


    public String postone(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result2 = HttpUtil.post(GATEWAY_HOST + "/api/request/postone", paramMap);
        return result2;
    }

    public Map<String, String> getHeader(String body) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        //为了安全密钥不进行传输
        //headers.put("secretKey",secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body);
        hashMap.put("timestamp ", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", getSign(body, secretKey));
        System.out.println("生成签字的body" + body);
        System.out.println("用到的密钥：" + secretKey);
        return hashMap;
    }

    public String postbody(User user, String url, String type) {
        String json = JSONUtil.toJsonStr(user);
        String result2 = null;
        if (type.equals("POST")) {
            result2 = HttpRequest.post(url)
                    .addHeaders(getHeader(json)) //请求头存放信息，业务层可以获取到
                    .body(json)
                    .execute().body();
        }
        if (type.equals("GET")) {
            result2 = HttpRequest.get(url)
                    .addHeaders(getHeader(json)) //请求头存放信息，业务层可以获取到
                    .form("txt", user.getName())
                    .execute().body();
        }
        return result2;
    }

    public String getImg(User user,String url) {
        String json = JSONUtil.toJsonStr(user);
        String resImgUrl = HttpRequest.get(url)
                .addHeaders(getHeader(json)) //请求头存放信息，业务层可以获取到
                .execute().body();
        return resImgUrl;
    }
}
